# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(ropls)
library(pROC)
library(egg)
library(randomForest)
library(Boruta)
library(magrittr)
library(e1071)
library(optparse)
library(tidyverse)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--mc", default = "meta_color.txt", type = "character", help = "metabolite color file"),
  make_option("--config", default = "config.csv", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
  select(c("SampleID", "ClassNote"))

head(sampleInfo)

configData <- read.csv(opt$config, header = F, stringsAsFactors = F) %>%
  set_colnames(c("arg", "value")) %>%
  column_to_rownames("arg")

rfTop <- configData["rfTop", "value"] %>%
  as.numeric()
rfTop

metaColDf <- read_tsv(opt$mc) %>%
  select(c("Class", "col"))
metaCols <- metaColDf %>%
  deframe()

parent <- paste0("./")
createWhenNoExist(parent)

fileName <- "RF_Imp_Rank.csv"

if (!file.exists(fileName)) {
  quit(status = 0)
}

plotData <- read_csv(fileName) %>%
  mutate(Metabolite = fct_reorder(Metabolite, MeanDecreaseGini, .desc = F)) %>%
  mutate(index = n():1)

indexs <- plotData %>%
  .$index
minIndex <- min(indexs)
maxIndex <- max(indexs)

lineY <- maxIndex - rfTop + 0.5
lineY

importances <- plotData %>%
  .$MeanDecreaseGini
maxImportance <- max(importances)

p <- ggplot(plotData, mapping = aes(x = MeanDecreaseGini, y = index, fill = Class)) +
  ylab("") +
  xlab("MeanDecreaseGini") +
  theme_bw(base_size = 8.8, base_family = "Times") +
  theme(axis.text.x = element_text(size = 10, hjust = 1, vjust = 1), legend.position = 'right',
        legend.text = element_text(size = 9), legend.title = element_text(size = 11), axis.text.y = element_text(size = 6),
        axis.title.y = element_text(size = 11), axis.title.x = element_text(size = 12),
        panel.border = element_rect(size = 0.75), panel.grid.minor.x = element_blank(), panel.grid.minor.y = element_blank()
  ) +
  geom_point(shape = 21, size = 4) +
  scale_fill_manual("Class", values = metaCols) +
  scale_y_continuous(breaks = plotData$index, labels = plotData$Metabolite, expand = c(0, 0),
                     limit = c(minIndex - 0.5, maxIndex + 0.5)) +
  geom_hline(aes(yintercept = lineY), colour = "black", linetype = 2, size = 0.375) +
  annotate("text", x = maxImportance, y = lineY + 0.3, label = str_c("Top ", rfTop), color = "black", hjust = 1,
           size = 3, family = "Times", vjust = 0)

pdfFileName <- paste0(parent, "/RF_Imp.pdf")
rowNum <- nrow(plotData)
minHeight<-1
height <- max(minHeight + (rowNum - 10) * 0.15, minHeight) + 2
ggsave(limitsize = FALSE, pdfFileName, p, width = 6, height = height)






